import MyIcon from '@/components/MyIcon';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import { AutoComplete, Card, Col, Empty, Input, Row } from 'antd';
import { ChangeEvent, useContext, useMemo } from 'react';
import { IAuthFirstRightList } from '../../type';
import { AuthorizationContext } from '../AuthHooks';
import { SearchOutlined, CloseOutlined } from '@ant-design/icons';

import cls from 'classnames';
import { loopArray } from '@/utils';

export const AuthFirstRightList: React.FC<IAuthFirstRightList> = ({
  firstMenuList,
}) => {
  const {
    prefixCls,
    leftTreeCheckRows,
    rightSearchValue,
    authGranDispatch,
    leftSelectKeys,
  } = useContext(AuthorizationContext); //获取 上下文

  // 搜索下拉菜单
  const autoOptionRight = useMemo(() => {
    let option: Record<string, any>[] = [];
    const tileTreeData = (data: Record<string, any>[]) => {
      data?.forEach((item) => {
        if (item?.name?.includes(rightSearchValue)) {
          // const name = item?.name;
          // const nameLength = name?.length;
          // const select = name?.search(rightSearchValue);
          // const searchLength = rightSearchValue?.length;
          // const afterStr = name?.slice(0, select);
          // const selectStr = rightSearchValue;
          // const beforeStr = name?.slice(select + searchLength, nameLength);
          option.push({
            value: item?.name,
            key: item?.id,
            // label: (
            //   <div>
            //     <span>{afterStr}</span>
            //     <span style={{ color: '#f50' }}>{selectStr}</span>
            //     <span>{beforeStr}</span>
            //   </div>
            // ),
          });
        }
      });
    };
    tileTreeData(leftTreeCheckRows);
    return option;
  }, [leftTreeCheckRows, rightSearchValue]);

  // 点击搜索
  const onAutoSelect = (value: string, option: any) => {
    const promise = new Promise((resolve, reject) => {
      const optionId = option?.key;
      // const targetNode = loopArray(leftTreeData)?.find((i) => i?.id == optionId);
      authGranDispatch({
        type: 'authGran-rightSearchValue',
        payload: value,
      });

      setTimeout(() => {
        scrollToAnchor(optionId);
      }, 1000);

      resolve(optionId);
    });
    promise.then((res: any) => {
      if (res) {
      }
    });
  };

  // 搜索框改变
  const onInputChangeRight = (e: ChangeEvent<HTMLInputElement>) => {
    authGranDispatch({
      type: 'authGran-rightSearchValue',
      payload: e.target.value,
    });
  };

  // 滚动定位
  const scrollToAnchor = (id: string) => {
    let anchorElement = document.getElementById(id + 'right');
    if (id) {
      anchorElement?.scrollIntoView({
        behavior: 'smooth',
        block: 'nearest',
        inline: 'start',
      });
    }
  };

  // 点击右侧删除选中的标签
  const delRightTag = (tagObj: any) => {
    if (tagObj?.resourceType == 0 || tagObj?.textType == 0) {
      let delIds = handDelChild([tagObj]); //要删除的id,如果是目录,删除子菜单
      let checkIDS = leftSelectKeys?.filter(
        (item: any) => !delIds?.includes(item),
      );
      let checkRows = leftTreeCheckRows?.filter((nodeItem: any) =>
        checkIDS?.includes(nodeItem?.id),
      );
      authGranDispatch({
        type: 'authGran-leftSelectKeys',
        payload: checkIDS,
      });
      authGranDispatch({
        type: 'authGran-leftTreeCheckRows',
        payload: checkRows,
      });
    } else {
      let leftKey = leftSelectKeys?.filter(
        (nodeItem: any) => nodeItem != tagObj?.id,
      ); //获取选中的 key
      let handleLeftKey = handleNoChildren(leftKey, tagObj); //处理当子节点全部没有选中时候,去除父节点选中效果
      // let rightRows = leftTreeCheckRows?.filter((nodeItem: any) => handleLeftKey?.includes(nodeItem?.id));
      let rightRows = leftTreeCheckRows?.filter((nodeItem: any) =>
        leftKey?.includes(nodeItem?.id),
      );
      authGranDispatch({
        type: 'authGran-leftTreeCheckRows',
        payload: rightRows,
      });
      authGranDispatch({
        type: 'authGran-leftSelectKeys',
        // payload: handleLeftKey,
        payload: leftKey,
      });
    }
  };

  // 处理当子节点全部没有选中时候,去除父节点选中效果
  const handleNoChildren = (idList: any[], onObj: any) => {
    let isHaveChild: any = [];
    let loopTree = (dataList: any) => {
      dataList?.forEach((item: any) => {
        if (onObj?.pID == item?.id) {
          isHaveChild = item?.children?.filter((itemChild: any) => {
            return idList?.includes(itemChild?.id);
          });
        }
      });
    };
    loopTree(firstMenuList);
    if (isHaveChild && isHaveChild?.length > 0) {
      return idList;
    } else {
      return idList?.filter((itemObj: any) => {
        return itemObj != onObj?.pID;
      });
    }
  };

  //处理删除的是目录的话 自己菜单也删除
  const handDelChild = (list: any[]) => {
    let delKey = loopArray(list);
    let keys: any[] = [];
    delKey?.forEach((item) => {
      keys?.push(item?.id);
    });
    return keys;
  };

  return (
    <Col span={11} style={{ height: '100%' }}>
      <Card
        className={prefixCls + 'contentCard'}
        bordered
        title={
          <>
            <Row style={{ display: 'flex', alignItems: 'center' }}>
              <Col span={8}>
                已选： {leftTreeCheckRows?.length} /{' '}
                {loopArray(firstMenuList)?.length}
              </Col>
              <Col span={16}>
                <AutoComplete
                  style={{ width: '100%' }}
                  options={autoOptionRight}
                  notFoundContent={
                    <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                  }
                  onSelect={onAutoSelect}
                >
                  <Input
                    suffix={<SearchOutlined />}
                    onChange={onInputChangeRight}
                    placeholder="请按名称搜索"
                    allowClear={true}
                  />
                </AutoComplete>
              </Col>
            </Row>
          </>
        }
      >
        <ScrollBarLayout
          style={{
            padding: '10px',
            height: '100%',
          }}
        >
          {/* <div style={{ paddingBottom: '10px' }}> */}
          {leftTreeCheckRows && leftTreeCheckRows.length > 0 ? (
            <>
              {leftTreeCheckRows.map((item: any, index: any) => {
                const name = item?.name ?? item?.text;
                const nameLength = name?.length;
                const select = name?.search(rightSearchValue);
                const searchLength = rightSearchValue?.length;
                const afterStr = name?.slice(0, select);
                const selectStr = rightSearchValue;
                const beforeStr = name?.slice(
                  select + searchLength,
                  nameLength,
                );
                const titleTree =
                  select > -1 && selectStr ? (
                    <span>
                      {afterStr}
                      <span style={{ color: '#f50' }}>{selectStr}</span>
                      {beforeStr}
                    </span>
                  ) : (
                    item?.name ?? item?.text
                  );
                return (
                  <div
                    style={{ paddingTop: index == 0 ? '0px' : '' }}
                    className={cls(prefixCls + 'step-cardRole-rightFather')}
                    id={item?.id + 'right'}
                    key={item?.id + 'right'}
                  >
                    <div
                      className={cls(prefixCls + 'step-cardRole-rightChild')}
                    >
                      <div
                        className={cls(
                          prefixCls + 'step-cardRole-rightChildIcon',
                        )}
                      >
                        <div style={{ margin: '0px 5px 0px 10px' }}>
                          <MyIcon type={item?.icon} />
                        </div>
                        <div style={{ padding: '5px 0px' }}>
                          {titleTree ?? '--'}
                        </div>
                      </div>
                      <span
                        style={{
                          margin: '0px 10px',
                          cursor: 'pointer',
                        }}
                        onClick={(e) => {
                          e?.stopPropagation();
                          delRightTag(item);
                        }}
                      >
                        <CloseOutlined />
                      </span>
                    </div>
                  </div>
                );
              })}
            </>
          ) : (
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
          )}
          {/* </div> */}
        </ScrollBarLayout>
      </Card>
    </Col>
  );
};
